#include "animationwindow.h"
#include <QPainter>
#include <QTimer>

AnimationWindow::AnimationWindow(QWidget *parent) : m_index(0), m_x(0), QWidget{parent}
{

}

void AnimationWindow::showBetScore(int bet)
{
    m_x = 0;
    if (bet == 1) {
        m_image.load(":/images/score1.png");
    } else if (bet == 2) {
        m_image.load(":/images/score2.png");
    } else if (bet == 3) {
        m_image.load(":/images/score3.png");
    }
    update(); //
    QTimer::singleShot(2000, this, &AnimationWindow::hide); // 只显示2s, 2s之后自动隐藏叫地主时显示的分数
}


// 显示顺子和连对的动画特效
void AnimationWindow::showSequence(Type type)
{
    m_x = 0;
    QString name = (type == Pair ? ":/images/liandui.png" : ":/images/shunzi.png");
    m_image.load(name);
    update();
    QTimer::singleShot(2000, this, &AnimationWindow::hide); // 显示2s之后将特效隐藏
}

// 显示炸弹或者王炸的动画特效
void AnimationWindow::showBomb(Type type)
{
    m_index = 0;
    m_x = 0;

    const int maxImage = (type == Type::Bomb ? 12 : 9);

    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=](){
        ++ m_index;

        if (m_index > maxImage) {
            m_index = maxImage;
            timer->stop();
            timer->deleteLater();
            hide();
        }

        QString name = (type == Type::Bomb ? QString(":/images/bomb_%1.png").arg(m_index) : QString(":/images/joker_bomb_%1.png").arg(m_index));
        m_image.load(name);
        update();
    });
    timer->start(60);
}

// 显示飞机的动态特效
void AnimationWindow::showPlane()
{
    m_x = width(); // 飞机显示的整个窗口
    m_image.load(":/images/plane_1.png");
    setFixedHeight(m_image.height());
    update();

    int step = width() / 5; // 将整个飞机的区域显示划分为5小块
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]() {
        // 每触发一次定时器，就让飞机移动5px
        static int dist = 0;    // 记录飞机移动的距离
        static int timers = 0;  // 触发定时器的次数，即对应飞机图片的编号
        dist += 5;
        if (dist >= step) {
            // 飞机已经从一个小分区移动到另外一个小分区
            dist = 0;
            ++ timers;
            QString name = QString(":/images/plane_%1.png").arg(timers % 5 + 1);
            m_image.load(name);
        }
        // 飞机从右向左飞，当整个飞机飞出窗口时，就可以暂停定时器，隐藏飞机的特效
        if (m_x <= -110) {
            timer->stop();
            timer->deleteLater();
            dist = 0;
            timers = 0;
            hide();
        }
        m_x -= 5; // 向左移动5px
        update();
    });
    timer->start(15);
}

void AnimationWindow::paintEvent(QPaintEvent *ev)
{
    Q_UNUSED(ev);
    QPainter p(this);
    p.drawPixmap(m_x, 0, m_image.width(), m_image.height(), m_image);
}
